import { db } from "./DataBase";
export class dbFunc {
    static async register(account: string, password: string) {
        const result = { errorcode: 0, userid: 0, nickname: '' }
        try {
            const data: any[] = await db.all("SELECT * FROM users WHERE account=?", [account])
            console.log('db_register:', data)
            if (data.length > 0) {
                result.errorcode = 1
            }
            else {
                const t: any[] = await db.all("SELECT MAX(id) as id FROM users")
                console.log('maxid:', t)
                result.userid = t[0].id + 10000
                await db.run("INSERT INTO users(userid,account,password,nickname,roomid) VALUES(?,?,?,?,?)", [result.userid, account, password, account, 0])
            }
        } catch (error) {
            result.errorcode = 2
            console.log(error);
        }
        finally {
            return result
        }

    }

    static async login(account: string, password: string) {
        const result = { errorcode: 0, userid: 0, nickname: '', roomid: 0 }
        try {
            const data: any[] = await db.all("SELECT * FROM users WHERE account=? AND password=?", [account, password])
            console.log('db_login:', data)
            if (data.length > 0) {
                result.userid = data[0].userid
                result.nickname = data[0].nickname
                result.roomid = data[0].roomid
                result.errorcode = 0
            }
            else {
                result.errorcode = 1
            }
        }
        catch (error) {
            result.errorcode = 2
            console.log(error);
        }
        finally {
            return result
        }
    }

    static async userEnter(roomid: number, userid: number) {
        try {
            await db.run("UPDATE users SET roomid=? WHERE userid=?", [roomid, userid])
        }
        catch (error) {
            console.log(error);
        }
    }

    static async getRoomUserInfos(roomid: number) {
        const result: { errorcode: number, userinfos: any[] } = { errorcode: 0, userinfos: [] }
        try {
            const data: any[] = await db.all("SELECT * FROM users WHERE roomid=?", [roomid])
            console.log('db_userInfo:', data)
            result.errorcode = 0
            if (data.length > 0) {
                result.userinfos = data as []
            }
        }
        catch (error) {
            result.errorcode = 1;
            console.log(error)
        }
        finally {
            return result
        }
    }

    static async userLeave(userid: number) {
        try {
            await db.run("UPDATE users SET roomid=0 WHERE userid=?", [userid])
        }
        catch (error) {
            console.log(error);
        }
    }
}
